package com.css.fxfzdzzh.util;

import com.css.fxfzdzzh.modules.surfaceRupture.entity.RealEarthquakeEntity;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.BeanInfo;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @author Dbj
 * @date 2023年04月10日  13:50
 */
public class Xml2ObjectUtil {
    public static RealEarthquakeEntity getRealEarthquakeEntity(String url){
        String tempUrl = HttpClientUtil.doPost(url);
        System.out.println(tempUrl);
        InputStream is = null;
        try {
            SAXReader reader = new SAXReader();
            is = new ByteArrayInputStream(tempUrl.getBytes("UTF-8"));
            Document doc = reader.read(is);
            Element root = doc.getRootElement();
            List<Element> article = root.elements("item");
            List<RealEarthquakeEntity> list=new ArrayList<>();
            for (Element element : article) {
                String cataId = element.elementText("cata_id");
                BigDecimal  earthQuakeLevel = new BigDecimal(element.elementText("magnitude"));
                BigDecimal latitude = new BigDecimal(element.elementText("epi_lat"));
                BigDecimal longitude = new BigDecimal(element.elementText("epi_lon"));
                BigDecimal sourceDepth = new BigDecimal(element.elementText("epi_depth"));
                String location = element.elementText("location_c");
                Date time = new Date(element.elementText("o_time"));
                RealEarthquakeEntity realEarthquakeEntity=new RealEarthquakeEntity(cataId,earthQuakeLevel,latitude,longitude,sourceDepth,location,time);
                list.add(realEarthquakeEntity);
            }
            RealEarthquakeEntity realEarthquakeEntity = new RealEarthquakeEntity();
            if(list.size()>0){
                //获取最近发生的地震信息
                realEarthquakeEntity = list.stream().max(Comparator.comparing(RealEarthquakeEntity::getTime)).get();
            }
            return realEarthquakeEntity;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
